package com.nx.platform.es.bean.modle.param;

import com.google.common.base.Enums;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Table;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Floats;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.bean.dto.RequestContext;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.common.Strings;

import java.util.List;
import java.util.Map;


/**
 * @author
 * @since 2016年10月15日
 */
public class FloatHandler implements ParamFieldHandler {

    @Override
    public void handle(RequestContext context, ImmutableMap<String, ?> fieldConfig,
                       Table<String, StatementOperator, List<String>> queryTable,
                       Table<String, StatementOperator, List<String>> paramsTable, Map<String, Object> paramsMap) {
        String fieldFace = MapUtils.getString(fieldConfig, "face");
        if (Strings.isNullOrEmpty(fieldFace)) {
            return;
        }
        List<String> fieldValue = paramsTable.get(fieldFace, StatementOperator.EQUAL);
        String clazz = MapUtils.getString(fieldConfig, "class");
        if (CollectionUtils.isNotEmpty(fieldValue)) {
            Object param = parse(clazz, fieldValue.get(0));
            if (param != null) {
                context.getTrace().append("&_param_").append(fieldFace).append(StatementOperator.EQUAL.getSymbol()).append(fieldValue.get(0));
                paramsMap.put(fieldFace, param);
            }
        }
    }

    protected Comparable<? extends Number> parse(String clazz, String str) {
        return Enums.getIfPresent(Parsers.class, clazz).or(Parsers.Double).parse(str);
    }

    enum Parsers {
        Float {
            @Override
            Comparable<? extends Number> parse(String str) {
                return Floats.tryParse(str);
            }
        },
        Double {
            @Override
            Comparable<? extends Number> parse(String str) {
                return Doubles.tryParse(str);
            }
        };

        abstract Comparable<? extends Number> parse(String str);

    }

}
